<template>
  <div class="purchase-products-list-component-page hospital-purchase-products">
    <div class="block">
      <header>
        <h2 class="required">
          {{ title ? title : '采购产品' }}
        </h2>
      </header>
      <section>
        <el-row class="block-item">
          <el-col :span="12">
            <!-- <div>&nbsp;</div> -->
            <el-button type="primary" @click="onOpenImportProduct">
              模板导入产品
            </el-button>
            <el-divider direction="vertical" />
            <el-button type="text" @click="onGetProductTemplate">
              模板下载
            </el-button>
          </el-col>
          <el-col :span="12" class="right">
            <el-button type="primary" @click="onOpenProductDialog">
              添加采购产品
            </el-button>
          </el-col>
        </el-row>
        <el-editable
          v-loading="productLoading"
          :columns="COLUMNS_PRODUCT"
          :payload="payload_products"
          :need-pagination="true"
          height="400"
          @reload="reloadData"
        >
          <template v-slot:default-productCount="{ row, $index }">
            <div>
              <el-input-number
                v-model="row.productCount"
                :step="1"
                step-strictly
                size="small"
                :min="1"
                :max="9999"
                @change="onChangeCount(row, $index)"
              />
            </div>
          </template>
          <template v-slot:default-opt="{ row, $index }">
            <a href="javascript:;" @click="onDeleteProduct(row, $index)">删除</a>
          </template>
          <!-- 给创建报台用的表格内表单 -->
        </el-editable>
      </section>
    </div>
    <upload ref="upload" :title-str="titleStr" :params="stepOneFormData" @complete="getUploadProducts" />
  </div>
</template>

<script>
import { ProductAddDialogService } from '~/components/hospital-purchase-order/purchase-products-list/product-dialog/product-add.dialog.module';
import * as CONSTS from './purchase-products-list.const';
import ElEditable from '@components/el-editable';
import { IndexService } from './purchase-products-list.service';
import { urlDownload } from '@const/utils';
const service = new IndexService();
import upload from '@/components/hospital-purchase-order/purchase-products-list/upload';
export default {
  components: {
    ElEditable,
    upload
  },
  props: {
    titleStr: {
      type: String,
      default: '批发采购'
    },
    isCreateBill: {
      type: Boolean
    },
    stepOneFormData: {
      type: Object
    },
    products: {
      type: Array
    },
    type: {
      type: String,
      default: 'default'
    },
    operationType: String,
    title: String,
    productLoading: Boolean
  },
  data() {
    return {
      ...CONSTS,
      _products: [],
      payload_products: {},
      pager: {
        number: 1,
        size: 20
      },
      // 由于更新数量的动态性，下标的切换要同步。故这样搞
      index: {
        start: 1,
        end: 1
      }
    };
  },
  computed: {
    productAddDialogService: function() {
      return new ProductAddDialogService(this.$axios, this.$store, { type: this.type });
    }
  },
  watch: {
    products: {
      handler: function(val, oldVal) {
        if (val !== undefined) {
          this._products = val;
          let startIndex = (this.pager.number - 1) * this.pager.size;
          let endIndex = this.pager.number * this.pager.size;
          this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getUploadProducts(payload) {
      let loadProductList = payload;
      console.log(loadProductList);
      if (loadProductList.length > 0) {
        this.updateProductData(payload, true);
      }
    },
    // 前端分页逻辑
    reloadData(pager) {
      let startIndex = (pager.number - 1) * pager.size;
      let endIndex = pager.number * pager.size;
      this.payload_products = service.getPayload(this._products, pager, startIndex, endIndex);
      this.pager = pager;
    },
    onDeleteProduct(row, index) {
      let startIndex = (this.pager.number - 1) * this.pager.size;
      let endIndex = this.pager.number * this.pager.size;
      this._products.splice(startIndex + index, 1);
      this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
      if (this.payload_products.content.length === 0) {
        // 如果当前获取的内容为空，那么要重新获取一下数据
        this.pager.number = this.pager.number - 1;
        if (this.pager.number <= 0) this.pager.number = 1;
        let startIndex = (this.pager.number - 1) * this.pager.size;
        let endIndex = this.pager.number * this.pager.size;
        this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
      }
      this.$emit('update:products', this._products);
    },
    onChangeCount(row, idx) {
      if (!row.productCount) {
        this.$nextTick(() => {
          row.productCount = 1;
        });
      }
      this.$emit('update:products', this._products);
    },
    onOpenProductDialog() {
      // 这里的formData传递完整的数据，再在子组件内整理成子级组件想要的数据格式，
      // 实际上这样做是“不好的”，但是由于数据的复杂度和混乱度，故此选择。
      // 再有一个原因是，产品搜索列表还需要一些额外的参数
      this.productAddDialogService
        .create({
          title: '添加采购产品',
          query: { operationType: this.operationType, formData: this.stepOneFormData },
          confirmButtonClickHandler: (data = {}) => {
            data.forEach(element => {
              this.$set(element, 'productCount', 1);
            });
            // console.log(JSON.stringify(data))
            this.updateProductData(data);
          }
        })
        .mount();
    },
    updateProductData(data, isImport) {
      this._products = service.reConcatSelectData(data, this._products, 'factoryItemNum', isImport);
      let startIndex = (this.pager.number - 1) * this.pager.size;
      let endIndex = this.pager.number * this.pager.size;
      this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
      this.$emit('update:products', this._products);
    },
    onOpenImportProduct() {
      this.$refs.upload.dialog_visible = true;
    },
    onGetProductTemplate() {
      urlDownload(
        'https://md.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/8qf28rs0tnjwufv3z38ukpz4bxjo483j.xlsx'
      );
    }
  }
};
</script>
<style lang="less">
  .el-input-number{
    width: 150px;
  }
  .hospital-purchase-products {
    .el-editable{
      flex: none !important;
      min-height: 400px;
    }
  }
</style>
